package com.powernode.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.powernode.constant.CategoryConstant;
import com.powernode.domain.Category;
import com.powernode.mapper.CategoryMapper;
import com.powernode.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
@CacheConfig(cacheNames = "com.powernode.service.impl.CategoryServiceImpl")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService{

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private CategoryService categoryService;

    @Override
    @Cacheable(key = CategoryConstant.CATEGORY_LIST)
    public List<Category> list() {
        return categoryMapper.selectList(new LambdaQueryWrapper<Category>().orderByDesc(Category::getSeq));
    }

    @Override
    @CacheEvict(key = CategoryConstant.CATEGORY_LIST)
    public boolean save(Category entity) {
        // 1. 获取parentId
        Long parentId = entity.getParentId();

        // 2. 判断是否为一级类目
        if (0 == parentId) {
            entity.setGrade(1);
        } else {
            entity.setGrade(2);
        }

        // 3. 补充字段
        entity.setRecTime(new Date());
        entity.setUpdateTime(new Date());
        entity.setShopId(1L);

        return categoryMapper.insert(entity) > 0;
    }

    @Override
    @CacheEvict(key = CategoryConstant.CATEGORY_LIST)
    public boolean updateById(Category entity) {

        // 1. 获取当前类目的原有的级别
        Category oldCategory = categoryMapper.selectById(entity.getCategoryId());
//        entity.setShopId(oldCategory.getShopId());
//        entity.setIcon(oldCategory.getIcon());
//        entity.setRecTime(oldCategory.getRecTime());
        entity.setUpdateTime(new Date());

        // 2. 原来的级别和父级
        Long oldParentId = oldCategory.getParentId();
        Integer oldGrade = oldCategory.getGrade();

        // 3. 获取更新后的父级
        Long nowParentId = (entity.getParentId() == null || entity.getParentId() == 0 || entity.getParentId() == entity.getCategoryId())
                ? 0 : entity.getParentId();
        entity.setParentId(nowParentId);

        // 4. 是否修改类目级别, 如果没修改级别说明只是修改了其他的属性直接改变即可

        // 如果以前的父id等于现在的父id，表明类目不变，但是如果有人将一级目录变为自己的子目录，也不改变
        if (nowParentId == oldParentId) {
            // 4.1 类目不变
            entity.setGrade(oldGrade);
            categoryMapper.updateById(entity);

        } else {
            // 4.2 类目改变，且类目从一级变为二级
            if (nowParentId != 0 && oldParentId == 0) {
                entity.setGrade(2);
                categoryMapper.updateById(entity);

                // 查询原来该一级目录下的，让其归并到新的一级下
                List<Category> categories = categoryMapper.selectList(new LambdaQueryWrapper<Category>()
                        .eq(Category::getParentId, entity.getCategoryId()));

                if (categories != null && categories.size() > 0) {
                    // 批量修改
                    categories.forEach(item -> {
                        item.setParentId(entity.getParentId());
                    });

                    categoryService.updateBatchById(categories);
                }

            // 4.3 类目改变，且类目从二级变为其他二级, 设置二级类目即可
            } else if (oldParentId != 0 && nowParentId != 0) {
                entity.setGrade(2);
                categoryMapper.updateById(entity);

            // 4.4 类目改变，且类目从二级变为一级
            } else if (nowParentId == 0 && oldParentId != 0) {
                entity.setGrade(1);
                categoryMapper.updateById(entity);
            }

        }

        return true;
    }


    @Override
    @CacheEvict(key = CategoryConstant.CATEGORY_LIST)
    @Transactional
    public boolean removeById(Serializable id) {
        // 1. 根据标识判断类目是几级类目
        Category category = categoryMapper.selectById(id);
        Integer grade = category.getGrade();

        // 2. 如果为一级目录则需要删除其二级类目
        if (grade == 1) {
            categoryMapper.delete(new LambdaQueryWrapper<Category>()
                    .eq(Category::getParentId, category.getCategoryId()));
        }


        return categoryMapper.deleteById(id) > 0;
    }
}
